package com.lzh.msm.controller;

import com.lzh.commonutils.CommonResult;
import com.lzh.commonutils.RandomUtils;
import com.lzh.msm.service.MsmService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/msm")
public class MsmController {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private MsmService msmService;
    @ApiOperation(value = "发送手机验证码")
    @GetMapping("/send")
    public CommonResult send(@RequestParam String phone) {
        //根据手机号码在redis中取出验证码
        String code1 = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code1)) return CommonResult.ok();
        String code = RandomUtils.createCode(true, 4);
        boolean result = msmService.send(phone,code);
        if (result) {
            //发送成功后将验证码保存在redis中并设置5分钟的过期时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return CommonResult.ok();
        }else {
            return CommonResult.error().message("验证码发送失败，请检查手机号是否正确！");
        }

    }
}
